<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/xizhongren8980/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/xizhongren8980/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/xizhongren8980/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/xizhongren8980/images/logo.svg" color="#222">

<link rel="stylesheet" href="/xizhongren8980/css/main.css">


<link rel="stylesheet" href="/xizhongren8980/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/xizhongren8980/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="概述mybatis是一个基于 java 的持久层框架（即Dao层），它的内部封装了 jdbd ，使得我们在开发的时候只需要关注 sql 本身，而不用花费过多精力去加载驱动、创建连接等繁杂的过程。总结起来就是编码更少，过程更简单了。">
<meta property="og:type" content="article">
<meta property="og:title" content="【MyBatis入门_01】之初识MyBatis">
<meta property="og:url" content="https://gitee.com/xizhongren8980/xizhongren8980.git/2020/06/04/%E3%80%90MyBatis%E5%85%A5%E9%97%A8%E3%80%91%E4%B9%8B%E5%88%9D%E8%AF%86MyBatis/index.html">
<meta property="og:site_name" content="一杯茶一包烟，一个BUG改一天">
<meta property="og:description" content="概述mybatis是一个基于 java 的持久层框架（即Dao层），它的内部封装了 jdbd ，使得我们在开发的时候只需要关注 sql 本身，而不用花费过多精力去加载驱动、创建连接等繁杂的过程。总结起来就是编码更少，过程更简单了。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200604193401.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200604195608.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200604202425.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200604204413.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200604205257.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200604210401.png">
<meta property="og:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200604212327.png">
<meta property="article:published_time" content="2020-06-04T13:46:55.041Z">
<meta property="article:modified_time" content="2020-06-10T05:07:07.354Z">
<meta property="article:author" content="MisterTian">
<meta property="article:tag" content="数据库">
<meta property="article:tag" content="MyBatis">
<meta property="article:tag" content="框架">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200604193401.png">

<link rel="canonical" href="https://gitee.com/xizhongren8980/xizhongren8980.git/2020/06/04/%E3%80%90MyBatis%E5%85%A5%E9%97%A8%E3%80%91%E4%B9%8B%E5%88%9D%E8%AF%86MyBatis/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>【MyBatis入门_01】之初识MyBatis | 一杯茶一包烟，一个BUG改一天</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/xizhongren8980/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">一杯茶一包烟，一个BUG改一天</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">收藏永不停止，学习永不开始</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/xizhongren8980/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/xizhongren8980/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/xizhongren8980/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/xizhongren8980/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/xizhongren8980/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/xizhongren8980/xizhongren8980.git/2020/06/04/%E3%80%90MyBatis%E5%85%A5%E9%97%A8%E3%80%91%E4%B9%8B%E5%88%9D%E8%AF%86MyBatis/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/xizhongren8980/images/head.jpg">
      <meta itemprop="name" content="MisterTian">
      <meta itemprop="description" content="一个小菜鸟">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一杯茶一包烟，一个BUG改一天">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          【MyBatis入门_01】之初识MyBatis
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-06-04 21:46:55" itemprop="dateCreated datePublished" datetime="2020-06-04T21:46:55+08:00">2020-06-04</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-06-10 13:07:07" itemprop="dateModified" datetime="2020-06-10T13:07:07+08:00">2020-06-10</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/xizhongren8980/categories/MyBatis/" itemprop="url" rel="index"><span itemprop="name">MyBatis</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h3><p>mybatis是一个基于 <code>java</code> 的持久层框架（即Dao层），它的内部封装了 <code>jdbd</code> ，使得我们在开发的时候只需要关注 <code>sql</code> 本身，而不用花费过多精力去加载驱动、创建连接等繁杂的过程。总结起来就是编码更少，过程更简单了。<a id="more"></a></p>
<h3 id="环境搭建"><a href="#环境搭建" class="headerlink" title="环境搭建"></a>环境搭建</h3><p>想要使用工具开发，那首先得要有工具才行。因此搭建 <code>mybatis</code> 环境是开发的第一步。</p>
<p>接下来利用 Maven 工程模板搭建一个 mybatis 环境。</p>
<h4 id="创建一个默认-Maven-工程"><a href="#创建一个默认-Maven-工程" class="headerlink" title="创建一个默认 Maven 工程"></a>创建一个默认 Maven 工程</h4><p>首先是选择 Maven —&gt;  next —&gt;  设置 GroupId , ArtifactId —&gt; 设置工程名和工程路径，然后点击 Finish 即可，创建结果如图所示</p>
<p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200604193401.png" alt="image-20200604193356337"></p>
<h4 id="配置-pom-xml-文件"><a href="#配置-pom-xml-文件" class="headerlink" title="配置 pom.xml 文件"></a>配置 pom.xml 文件</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--设置打包方式--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">packaging</span>&gt;</span>jar<span class="tag">&lt;/<span class="name">packaging</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--导入依赖的 jar 包--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--导入mybatis --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.mybatis<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.5.4<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--导入mysql数据库驱动--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>mysql<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mysql-connector-java<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>8.0.15<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--导入日志组件--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>log4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>log4j<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.2.12<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--导入测试包--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>junit<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>junit<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.13<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">scope</span>&gt;</span>test<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="创建-log4j-的配置文件-log4j-properties"><a href="#创建-log4j-的配置文件-log4j-properties" class="headerlink" title="创建 log4j 的配置文件 log4j.properties"></a>创建 log4j 的配置文件 log4j.properties</h4><figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Set root category priority to INFO and its only appender to CONSOLE.</span></span><br><span class="line"><span class="comment">#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal</span></span><br><span class="line"><span class="meta">log4j.rootCategory</span>=<span class="string">debug, CONSOLE, LOGFILE</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># Set the enterprise logger category to FATAL and its only appender to CONSOLE.</span></span><br><span class="line"><span class="meta">log4j.logger.org.apache.axis.enterprise</span>=<span class="string">FATAL, CONSOLE</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># CONSOLE is set to be a ConsoleAppender using a PatternLayout.</span></span><br><span class="line"><span class="meta">log4j.appender.CONSOLE</span>=<span class="string">org.apache.log4j.ConsoleAppender</span></span><br><span class="line"><span class="meta">log4j.appender.CONSOLE.layout</span>=<span class="string">org.apache.log4j.PatternLayout</span></span><br><span class="line"><span class="meta">log4j.appender.CONSOLE.layout.ConversionPattern</span>=<span class="string">%d&#123;ISO8601&#125; %-6r [%15.15t] %-5p %30.30c %x - %m\n</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># LOGFILE is set to be a File appender using a PatternLayout.</span></span><br><span class="line"><span class="meta">log4j.appender.LOGFILE</span>=<span class="string">org.apache.log4j.FileAppender</span></span><br><span class="line"><span class="meta">log4j.appender.LOGFILE.File</span>=<span class="string">d:axis.log</span></span><br><span class="line"><span class="meta">log4j.appender.LOGFILE.Append</span>=<span class="string">true</span></span><br><span class="line"><span class="meta">log4j.appender.LOGFILE.layout</span>=<span class="string">org.apache.log4j.PatternLayout</span></span><br><span class="line"><span class="meta">log4j.appender.LOGFILE.layout.ConversionPattern</span>=<span class="string">%d&#123;ISO8601&#125; %-6r [%15.15t] %-5p %30.30c %x - %m\n</span></span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200604195608.png" alt="image-20200604195604916"></p>
<h3 id="建立数据库表-book"><a href="#建立数据库表-book" class="headerlink" title="建立数据库表 book"></a>建立数据库表 book</h3><p>要使用 mybatis 与数据库进行数据交互，首先得有数据库表才行。</p>
<ul>
<li><p>建立数据表 t_book</p>
</li>
<li><p>插入数据项</p>
<img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200604202425.png" alt="image-20200604202407494"  />

</li>
</ul>
<h3 id="编写实体类-Book"><a href="#编写实体类-Book" class="headerlink" title="编写实体类 Book"></a>编写实体类 Book</h3><p>Book类的属性名称要与数据库中的字段相同。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xizhongren.domain;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.Serializable;</span><br><span class="line"><span class="keyword">import</span> java.math.BigDecimal;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Book</span> <span class="keyword">implements</span> <span class="title">Serializable</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> Integer id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> BigDecimal price;</span><br><span class="line">    <span class="keyword">private</span> String author;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>实体类位于 java\com\xizhongren\domain 路径下，然后再生成其构造方法、 Getter 和 Setter 方法 以及 toString()方法。</p>
<h3 id="创建-mybatis-主配置文件-SqlMapConfig-xml"><a href="#创建-mybatis-主配置文件-SqlMapConfig-xml" class="headerlink" title="创建 mybatis 主配置文件 SqlMapConfig.xml"></a>创建 mybatis 主配置文件 SqlMapConfig.xml</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">configuration</span></span></span><br><span class="line"><span class="meta">        <span class="meta-keyword">PUBLIC</span> <span class="meta-string">"-//mybatis.org//DTD Config 3.0//EN"</span></span></span><br><span class="line"><span class="meta">        <span class="meta-string">"http://mybatis.org/dtd/mybatis-3-config.dtd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">configuration</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--配置环境--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">environments</span> <span class="attr">default</span>=<span class="string">"mysql"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--配置mysql环境--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">environment</span> <span class="attr">id</span>=<span class="string">"mysql"</span>&gt;</span></span><br><span class="line">            <span class="comment">&lt;!--配置事物类型--&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">transactionManager</span> <span class="attr">type</span>=<span class="string">"JDBC"</span>&gt;</span><span class="tag">&lt;/<span class="name">transactionManager</span>&gt;</span></span><br><span class="line">            <span class="comment">&lt;!--配置数据源（连接池）--&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">dataSource</span> <span class="attr">type</span>=<span class="string">"POOLED"</span>&gt;</span></span><br><span class="line">                <span class="comment">&lt;!--配置链接数据库的四个基本信息--&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"driver"</span> <span class="attr">value</span>=<span class="string">"com.mysql.cj.jdbc.Driver"</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"url"</span> <span class="attr">value</span>=<span class="string">"jdbc:mysql://localhost:3306/mybatis?useSSL=false"</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"username"</span> <span class="attr">value</span>=<span class="string">"root"</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"password"</span> <span class="attr">value</span>=<span class="string">"123456"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">dataSource</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">environment</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">environments</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">configuration</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200604204413.png" alt="image-20200604204409585"></p>
<h3 id="创建书籍的持久层（dao）接口-BookDao"><a href="#创建书籍的持久层（dao）接口-BookDao" class="headerlink" title="创建书籍的持久层（dao）接口 BookDao"></a>创建书籍的持久层（dao）接口 BookDao</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xizhongren.dao;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.xizhongren.domain.Book;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">BookDao</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**查询所有图书</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Param</span> []</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> java.util.List&lt;com.xizhongren.domain.Book&gt;</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">List&lt;Book&gt; <span class="title">findAll</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="创建-BookDao-的映射配置文件-BookDao-xml"><a href="#创建-BookDao-的映射配置文件-BookDao-xml" class="headerlink" title="创建 BookDao 的映射配置文件 BookDao.xml"></a>创建 BookDao 的映射配置文件 BookDao.xml</h3><p>BookDao.xml 文件目录结构如图，一定要与接口一一对应。</p>
<p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200604205257.png" alt="image-20200604205255340"></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">mapper</span></span></span><br><span class="line"><span class="meta">        <span class="meta-keyword">PUBLIC</span> <span class="meta-string">"-//mybatis.org//DTD Mapper 3.0//EN"</span></span></span><br><span class="line"><span class="meta">        <span class="meta-string">"http://mybatis.org/dtd/mybatis-3-mapper.dtd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--namespace 必须是接口的全限定类名--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">"com.xizhongren.dao.BookDao"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--id 表示的是接口中具体的方法，resultType表示的是查询返回结果封装对象的类型--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"findAll"</span> <span class="attr">resultType</span>=<span class="string">"com.xizhongren.domain.Book"</span>&gt;</span></span><br><span class="line">        select * from t_book;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="向主配置文件-SqlMapConfig-xml-文件中添加-BookDao-xml-映射文件位置"><a href="#向主配置文件-SqlMapConfig-xml-文件中添加-BookDao-xml-映射文件位置" class="headerlink" title="向主配置文件 SqlMapConfig.xml 文件中添加 BookDao.xml 映射文件位置"></a>向主配置文件 SqlMapConfig.xml 文件中添加 BookDao.xml 映射文件位置</h3><p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200604210401.png" alt="image-20200604210358691"></p>
<p>这里有个细节需要注意，在资源路径下，其路径写法不是用 <code>.</code> 进行分隔，而是使用 <code>/</code> ，也就是说，<code>com.xizhongren.dao</code>  在创建包时表示的是一个三级结构，而在创建目录的时候表示的是一个一级目录。</p>
<h3 id="编写测试类-com-xizhongren-test-MybatisTest"><a href="#编写测试类-com-xizhongren-test-MybatisTest" class="headerlink" title="编写测试类 com.xizhongren.test.MybatisTest"></a>编写测试类 com.xizhongren.test.MybatisTest</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.xizhongren.test;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.xizhongren.dao.BookDao;</span><br><span class="line"><span class="keyword">import</span> com.xizhongren.domain.Book;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.io.Resources;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.session.SqlSession;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.session.SqlSessionFactory;</span><br><span class="line"><span class="keyword">import</span> org.apache.ibatis.session.SqlSessionFactoryBuilder;</span><br><span class="line"><span class="keyword">import</span> org.junit.Test;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.io.InputStream;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@ClassName</span>: MybatisTest</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Auther</span>: 戏中人</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>: 2020/6/4 21:16</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span>:mybatis入门案例</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MybatisTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">findAll</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="comment">//1.读取配置文件</span></span><br><span class="line">        InputStream inputStream = Resources.getResourceAsStream(<span class="string">"SqlMapConfig.xml"</span>);</span><br><span class="line">        <span class="comment">//2.创建SqlSessionFactory工厂</span></span><br><span class="line">        SqlSessionFactoryBuilder builder = <span class="keyword">new</span> SqlSessionFactoryBuilder();</span><br><span class="line">        SqlSessionFactory factory = builder.build(inputStream);</span><br><span class="line">        <span class="comment">//3.使用工厂生产SqlSession对象</span></span><br><span class="line">        SqlSession session = factory.openSession();</span><br><span class="line">        <span class="comment">//4.使用SqlSession创建Dao接口的代理对象</span></span><br><span class="line">        BookDao bookDao = session.getMapper(BookDao<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">        <span class="comment">//5.使用代理对象执行方法</span></span><br><span class="line">        List&lt;Book&gt; books = bookDao.findAll();</span><br><span class="line">        <span class="keyword">for</span> (Book book : books) &#123;</span><br><span class="line">            System.out.println(book);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//6.释放资源</span></span><br><span class="line">        session.close();</span><br><span class="line">        inputStream.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com//xizhongren8980/BlogImages/raw/master/imgs/20200604212327.png" alt="image-20200604212324942"></p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><ul>
<li><p>mybatis 环境搭建主要步骤：</p>
<ol>
<li><p>创建 Maven 工程并导入相应 jar 包坐标</p>
</li>
<li><p>创建与数据表对应的实体类和 dao 的接口</p>
</li>
<li><p>创建 Mybatis 的主配置文件</p>
<p>SqlMapConfig.xml</p>
</li>
<li><p>创建映射配置文件</p>
<p>BookDao.xml</p>
</li>
</ol>
</li>
</ul>
<ul>
<li><p>环境搭建注意事项</p>
<ol>
<li><p>创建 BookDao.xml 和 BookDao.java 时名称相同是个人习惯，也可命名为 BookMapper.xml</p>
</li>
<li><p>在 IDEA 中创建目录和包时，要额外注意其区别</p>
</li>
<li><p>mybatis 的映射配置文件必须和 dao 接口的包结构相同</p>
<p>包在创建时，com.xizhongren.dao是三级结构</p>
<p>目录创建时，com.xizhongren.dao是一级结构，com/xizhongren.dao 才是三级结构</p>
</li>
<li><p>映射文件中的 mapper 标签中的 namespace 属性取值必须是 dao 的全限定类名</p>
</li>
<li><p>映射配置文件的操作配置(例如select 标签) ，其 id 取值必须是 dao 接口对应的方法名</p>
</li>
</ol>
</li>
</ul>
<p>mybatis 的入门使用方法就写到这里了，希望能通过这个入门案例更加熟悉mybatis 的使用方法以及执行过程。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/xizhongren8980/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/" rel="tag"># 数据库</a>
              <a href="/xizhongren8980/tags/MyBatis/" rel="tag"># MyBatis</a>
              <a href="/xizhongren8980/tags/%E6%A1%86%E6%9E%B6/" rel="tag"># 框架</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/xizhongren8980/2020/06/04/Maven%E6%96%B0%E6%89%8B%E5%85%A5%E9%97%A8/" rel="prev" title="Maven新手入门">
      <i class="fa fa-chevron-left"></i> Maven新手入门
    </a></div>
      <div class="post-nav-item">
    <a href="/xizhongren8980/2020/06/06/%E3%80%90MyBatis%E5%85%A5%E9%97%A8%E3%80%91%E4%B9%8B%E5%A2%9E%E5%88%A0%E6%94%B9%E6%9F%A5%E6%93%8D%E4%BD%9C/" rel="next" title="【MyBatis入门_02】之增删改查操作">
      【MyBatis入门_02】之增删改查操作 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#概述"><span class="nav-number">1.</span> <span class="nav-text">概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#环境搭建"><span class="nav-number">2.</span> <span class="nav-text">环境搭建</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#创建一个默认-Maven-工程"><span class="nav-number">2.1.</span> <span class="nav-text">创建一个默认 Maven 工程</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#配置-pom-xml-文件"><span class="nav-number">2.2.</span> <span class="nav-text">配置 pom.xml 文件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#创建-log4j-的配置文件-log4j-properties"><span class="nav-number">2.3.</span> <span class="nav-text">创建 log4j 的配置文件 log4j.properties</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#建立数据库表-book"><span class="nav-number">3.</span> <span class="nav-text">建立数据库表 book</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#编写实体类-Book"><span class="nav-number">4.</span> <span class="nav-text">编写实体类 Book</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建-mybatis-主配置文件-SqlMapConfig-xml"><span class="nav-number">5.</span> <span class="nav-text">创建 mybatis 主配置文件 SqlMapConfig.xml</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建书籍的持久层（dao）接口-BookDao"><span class="nav-number">6.</span> <span class="nav-text">创建书籍的持久层（dao）接口 BookDao</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建-BookDao-的映射配置文件-BookDao-xml"><span class="nav-number">7.</span> <span class="nav-text">创建 BookDao 的映射配置文件 BookDao.xml</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#向主配置文件-SqlMapConfig-xml-文件中添加-BookDao-xml-映射文件位置"><span class="nav-number">8.</span> <span class="nav-text">向主配置文件 SqlMapConfig.xml 文件中添加 BookDao.xml 映射文件位置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#编写测试类-com-xizhongren-test-MybatisTest"><span class="nav-number">9.</span> <span class="nav-text">编写测试类 com.xizhongren.test.MybatisTest</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#总结"><span class="nav-number">10.</span> <span class="nav-text">总结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="MisterTian"
      src="/xizhongren8980/images/head.jpg">
  <p class="site-author-name" itemprop="name">MisterTian</p>
  <div class="site-description" itemprop="description">一个小菜鸟</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/xizhongren8980/archives/">
        
          <span class="site-state-item-count">57</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/xizhongren8980/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/xizhongren8980/tags/">
          
        <span class="site-state-item-count">101</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://mistertian8980.github.io/" title="https:&#x2F;&#x2F;mistertian8980.github.io&#x2F;" rel="noopener" target="_blank">Github博客</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">MisterTian</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script size="300" alpha="0.6" zIndex="-1" src="/xizhongren8980/lib/canvas-ribbon/canvas-ribbon.js"></script>
  <script src="/xizhongren8980/lib/anime.min.js"></script>
  <script src="/xizhongren8980/lib/velocity/velocity.min.js"></script>
  <script src="/xizhongren8980/lib/velocity/velocity.ui.min.js"></script>

<script src="/xizhongren8980/js/utils.js"></script>

<script src="/xizhongren8980/js/motion.js"></script>


<script src="/xizhongren8980/js/schemes/pisces.js"></script>


<script src="/xizhongren8980/js/next-boot.js"></script>


  <script defer src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/three.min.js"></script>
    <script defer src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/canvas_lines.min.js"></script>


  




  
<script src="/xizhongren8980/js/local-search.js"></script>













  

  

</body>
</html>
